package com.gsq.learning.mybatisplugin.plugin.interceptor;

import com.gsq.learning.mybatisplugin.exception.RouteTableNoExistException;
import com.mysql.jdbc.exceptions.MySQLSyntaxErrorException;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.Properties;

@Intercepts({@Signature(
        type = Executor.class,
        method = "query",
        args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class MyExecutorInterceptor implements Interceptor {
    private static final String MSG = "octopus route table info is not exit!";

    @Override
    public Object intercept(Invocation arg0) throws Throwable {
        Executor target = (Executor) arg0.getTarget();
        System.out.println("======> MyExecutorInterceptor：" + target);

        Object obj = null;
        try {
            obj = arg0.proceed();
        } catch (Throwable e) {
            if (e.getCause() instanceof MySQLSyntaxErrorException) {
                MySQLSyntaxErrorException ex = (MySQLSyntaxErrorException) e.getCause();
                System.out.println("====" + ex.getErrorCode());
                System.out.println("====" + ex.getSQLState());
                System.out.println("====" + ex.getMessage());
                System.out.println("====" + ex.getCause());
                if (MSG.equals(ex.getMessage())) {
                    throw new RouteTableNoExistException();
                }
            }
        }
        return obj;
    }

    @Override
    public Object plugin(Object arg0) {
        return Plugin.wrap(arg0, this);
    }

    @Override
    public void setProperties(Properties arg0) {
        System.out.println("======> env value: " + arg0.getProperty("names"));
    }

}
